;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.GuaranteesApply", [])
        .controller("GuaranteesApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "ybConfig", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", "$stateParams", function ($scope, $state, ybWidget, ybHttp, ybConfig, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter, $stateParams) {
            $scope.activeFlag = [true, false, false];
            $scope.showDatepickerBegin = false;
            $scope.showDatepickerEnd = false;
            $scope.showDatedeliveryReceiptStart = false;
            $scope.showDatedeliveryReceiptEnd = false;
            $scope.submitted = false;
            $scope.viewModel = null
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {
                seller: true
            };
            $scope.btnType = false
            $scope.dataList = [];
            $scope.deliveryWayList = [];
            var tabFlag = {
                0: "三包申请详情",
                1: "新增三包申请",
                2: "编辑三包申请"
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/threeGuaranteesPur/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/threeGuaranteesPur/exportAll")
            };
            $scope.sendMethodList = [];
            $scope.billStateList = [];
            $scope.tableConfig = {
                fixedWidth: 370,
                scrollWidth: 1400,
                tableCol: [
                    {
                        type: "",
                        name: "申请单号",
                        dataField: "purchaseNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购金额",
                        dataField: "totalPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货方式",
                        dataField: "deliveryTypeName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "applicationName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "realAuditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "realAuditDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "applicationDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outStatusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditNote",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备件申请说明",
                        dataField: "crmNote",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务类型",
                        dataField: "serviceType",
                        width: 120,
                        isShow: $scope.isNJ,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务网点",
                        dataField: "serviceSite",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否返厂",
                        dataField: "isReturn",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "outDate",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "序列号",
                        dataField: "factoryNumber",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "是否借件",
                        dataField: "borrowShow",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "备注说明",
                        dataField: "note",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "调拨原因",
                        width: 120,
                        dataField: "crmTransferReasonDesc",
                        isShow: $scope.isDL || $scope.isZHL
                    },
                    {
                        name: "省",
                        dataField: "province",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "市",
                        dataField: "city",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "领导审核状态",
                        dataField: "leaderAuditStatusShow",
                        width: 120,
                        isShow: $scope.isJCH || $scope.isNY,
                        isFixed: false
                    },
                    {
                        name: "领导",
                        dataField: "deptLeaderName",
                        width: 120,
                        isShow: $scope.isJCH || $scope.isNY,
                        isFixed: false
                    },
                    {
                        name: "领导审核意见",
                        dataField: "leaderAuditNote",
                        width: 120,
                        isShow: $scope.isJCH || $scope.isNY,
                        isFixed: false
                    },
                    {
                        name: "领导审核日期",
                        dataField: "leaderAuditDateShow",
                        width: 120,
                        isShow: $scope.isJCH || $scope.isNY,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 250,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                fixedWidth: 340,
                scrollWidth: 870,
                tableCol: [
                    {
                        name: "序号",
                        width: 60,
                        dataField: "rowNo",
                        isShow: false,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "零件编号",
                        width: 100,
                        dataField: "materialsNo",
                        isShow: true,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 180,
                        dataField: "materialsDesc",
                        isShow: true,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "领料单号",
                        width: 100,
                        dataField: "transferBillNo",
                        isShow: false
                    },
                    {
                        name: "领料单状态",
                        width: 100,
                        dataField: "transferStatusName",
                        isShow: false
                    },
                    {
                        name: "参考单价(￥)",
                        width: 120,
                        dataField: "price",
                        isShow: true,
                        needInput: !!$scope.isNJ
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "purchaseQty",
                        isShow: true,
                        needInput: true
                    },
                    {
                        name: "服务库存",
                        width: 100,
                        dataField: "fwAmount",
                        isShow: false
                    },
                    {
                        name: "服务非条码库存",
                        width: 100,
                        dataField: "fwFtmAmount",
                        isShow: false
                    },
                    {
                        name: "备件库存",
                        width: 100,
                        dataField: "bjAmount",
                        clickFn: "selectWarehouse",
                        isShow: false
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        dataField: "dcAmount",
                        clickFn: "selectWarehouse",
                        isShow: false
                    },
                    {
                        name: "领料仓库",
                        width: 100,
                        dataField: "warehouseCode",
                        isShow: false
                    },
                    {
                        name: "领料库区",
                        width: 100,
                        dataField: "areaCode",
                        isShow: false
                    },
                    {
                        name: "调拨数量",
                        width: 100,
                        dataField: "transferAmount",
                        isShow: false,
                        needInput: true
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "amount",
                        isShow: true,
                        clickFn: "alterReport",
                        needInput: false
                    },
                    {
                        name: "可用库存",
                        width: 100,
                        dataField: "warehouseInventoryEnableNum",
                        isShow: false
                    },
                    {
                        name: "需求差额",
                        width: 100,
                        dataField: "demandShortfall",
                        isShow: false
                    },
                    {
                        name: "已建出库数量",
                        width: 100,
                        dataField: "deliveryQty",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "实际出库数量",
                        width: 100,
                        dataField: "realQty",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "合计(￥)",
                        width: 100,
                        dataField: "totalPrice",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "供货商名称",
                        width: 100,
                        dataField: "supplierName",
                        isShow: false
                    },
                    {
                        name: "生产批次号",
                        width: 100,
                        dataField: "batchNo",
                        isShow: false
                    },
                    {
                        name: "SAP预留号",
                        width: 120,
                        dataField: "reservedOrder",
                        isShow: false
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };

            var btnPermissionCode = {
                guaranteesApplyAdd: window.ActionCode.guaranteesApplyAdd,
                guaranteesApplyDel: window.ActionCode.guaranteesApplyDel,
                guaranteesApplyEdit: window.ActionCode.guaranteesApplyEdit,
                guaranteesApplyAdjust: window.ActionCode.guaranteesApplyAdjust,
                guaranteesApplyRevert: window.ActionCode.guaranteesApplyRevert,
                guaranteesApplyAudit: window.ActionCode.guaranteesApplyAudit,
                guaranteesApplyExport: window.ActionCode.guaranteesApplyExport,
                batchImport: window.ActionCode.batchImport
            };

            $scope.btnPermission = {
                guaranteesApplyAdd: true,
                guaranteesApplyDel: true,
                guaranteesApplyEdit: true,
                guaranteesApplyAudit: true,
                guaranteesApplyRevert: true,
                guaranteesApplyExport: true,
                guaranteesApplyAdjust: true,
                batchImport: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.toolbarConfig = {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                };
                $scope.detailFlag = [true, true];

                handleSpecialTabCol(false, true, true);
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'rowNo').isShow = false;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'warehouseInventoryEnableNum').isShow = false;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'demandShortfall').isShow = false;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'estimatedShippingDateShow').isShow = true;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'standDeliveryTime').isShow = true;
            }

            function handleSpecialTabCol(showFlag, purchaseInputFlag, transferInputFlag) {
                if (!$scope.isJCH) return;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'purchaseQty').needInput = purchaseInputFlag;
                 // 农机定制
                $scope.isNJ && (ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'price').needInput = purchaseInputFlag)
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferAmount').needInput = transferInputFlag;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferBillNo').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferStatusName').isShow = showFlag;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'fwAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'fwFtmAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'bjAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'dcAmount').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'warehouseCode').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'areaCode').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'transferAmount').isShow = showFlag;

                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'supplierName').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'batchNo').isShow = showFlag;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'reservedOrder').isShow = showFlag;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/threeGuaranteesPur/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                for (var key in $scope.condition) {
                    if ($scope.condition[key] == "") {
                        $scope.condition[key] = undefined;
                    }
                }
                param.filters = $scope.condition;
                param.filters.seller = true;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    let ldstatus= {
                        0:"待领导审核",
                        1:"领导已审核",
                        2:"领导已拒绝"
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.outStatusDesc = $filter("ProgressStatus")(item.status, 'outDepot');
                        item.realAuditDateShow = $filter("YbDate")(item.realAuditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.applicationDateShow = $filter("YbDate")(item.applicationDate, 'yyyy-MM-dd HH:mm:ss');
                        item.outDate = $filter("YbDate")(item.outDate, 'yyyy-MM-dd HH:mm:ss');
                        item.borrowShow = $filter("TrueOrFalse")(item.borrow);
                        item.leaderAuditDateShow = $filter("YbDate")(item.leaderAuditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.leaderAuditStatusShow = ldstatus[item.leaderAuditStatus]
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType, fieldName) {
                switch (fnType) {
                    case "viewDetail":
                        ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'amount').isShow = false;
                        viewDetail(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "selectWarehouse":
                        selectWarehouse(item, fieldName);
                    default:
                        break;
                }
            };

            function getOrderStatues() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "SPZT"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.billStateList = resp.value;
                })
            }

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            function selectWarehouse(item, fieldName) {
                if (!item[fieldName]) return;

                let wType = ''
                switch(fieldName) {
                    case "fwAmount":
                        wType = 'fwInfo'
                        break;
                    case "fwFtmAmount":
                        wType = 'fwFtmInfo'
                        break;
                    case "bjAmount":
                        wType = 'bjInfo'
                        break;
                    case "dcAmount":
                        wType = 'dcInfo'
                        break;
                }
                const stockType = item.stockInfo[wType].stockType
                ybWidget.DataSelector({
                    title: '库存',
                    url: '/warehouseInventory/listWarehouseInfoByMaterials',
                    otherParams: { materialsNo: item.materialsNo, stockType },
                    isNotFilterParam: true,
                    fields: [
                        {
                            name: '仓库',
                            dataField: 'warehouseCode',
                            width: "40%"
                        },
                        {
                            name: '库区',
                            dataField: 'areaCode',
                            width: "40%"
                        },
                        {
                            name: '数量',
                            dataField: 'qty',
                            width: "20%"
                        },
                    ]
                }).then(function (data) {
                    item.stockType = stockType
                    item.warehouseCode = data.warehouseCode
                    item.areaCode = data.areaCode
                    item.transferAmount = data.qty == 0 ? item.purchaseQty : Math.min(item.purchaseQty, data.qty);
                    $scope.checkTransferAmount(item, 'transferAmount');
                })
            }

            $scope.clearWarehouseAndArea = function(item) {
                item.warehouseCode = '';
                item.areaCode = '';
                item.transferAmount = null;
                item.transferAmountErr = false;
                item.transferAmountExceedErr = false;
                item.transferAmountShowErr = false;
            }

            $scope.searchAddress = function (receiverName, purchaseOrgId) {
                if (!purchaseOrgId) {
                    ybWidget.ShowToaster('warning', '请先选择客户');
                    return;
                }
                ybWidget.SelectDeliveryAddress({
                    deliveryName: receiverName,
                    clientReceiveInfo: $scope.sapNum,
                    clientOrgId: purchaseOrgId,
                    supplierOrgId: $scope.orderObj.headerInfo.orgId
                }).then(function (data) {
                    $scope.orderObj.headerInfo.receiverName = data.receiverName;
                    $scope.orderObj.headerInfo.receiverPhone = data.receiverTel;
                    $scope.orderObj.headerInfo.receiverAddress = data.receiverAddress;
                });
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: true
                };
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };


            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.detailList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.detailList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.detailList[i].isChecked) {
                            $scope.orderObj.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.batchDel = function () {
                var deleteList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        deleteList.push(item.id);
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除的三包申请', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/threeGuaranteesPur/delete";
                    ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/threeGuaranteesPur/delete";
                    ybHttp.Post(service, reqUrl, [id]).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.batchImport = function (id) {
                var tmpUrl = "/threeGuaranteesPur/downloadTemplate?id="+id;
                var importUrl = "/threeGuaranteesPur/importBatchInfo?id="+id;
                var param = {
                    name: "批次号",
                    templateReqService: "device",
                    templateReqUrl: tmpUrl,
                    importReqService: "device",
                    importReqUrl: importUrl,
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.orderObj.headerInfo.applicationDate = +new Date();
                $scope.orderObj.headerInfo.orgId = $scope.curOrgId;
                $scope.orderObj.headerInfo.supplierOrgName = $scope.curOrg.companyName;
                $scope.orderObj.headerInfo.applicationName = $scope.curUser.name;
                $scope.orderObj.headerInfo.applicationPhone = $scope.curUser.mobile;
                $scope.orderObj.headerInfo.planDeliveryReceiptTime= $filter("YbDate")(new Date(), 'yyyy-MM-dd HH:mm:ss');
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'estimatedShippingDateShow').isShow = false;
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'standDeliveryTime').isShow = false;

                $scope.changeTab(2);
                $scope.orderObj.headerInfo.isReturn = '否'; // wangcan:增加是否返厂-默认否
                $scope.fileList = [];
            };


            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/threeGuaranteesPur/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    setMaterialDesc();
                    return resp.value;
                });
            }

            $scope.checkDate = function (item, start, end) {
                if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                    return;
                }
                if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    return;
                }
                if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                    item[end] = ybWidget.FormatEndDate(item[end]);
                    return;
                }
                var tmpTime = item[start];
                if (item[end] < item[start]) {
                    item[start] = ybWidget.FormatStartDate(item[end]);
                    item[end] = ybWidget.FormatEndDate(tmpTime);
                } else {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    item[end] = ybWidget.FormatEndDate(item[end]);
                }
            };

            function handleMaterialDetailsWhenSourceType1(tInputFlag) {
                handleSpecialTabCol(true, false, tInputFlag);
                angular.forEach($scope.orderObj.detailList, r => {
                    const si = r.stockInfo;
                    if (si) {
                        r.fwAmount = si.fwInfo && si.fwInfo.amount;
                        r.fwFtmAmount = si.fwFtmInfo && si.fwFtmInfo.amount;
                        r.bjAmount = si.bjInfo && si.bjInfo.amount;
                        r.dcAmount = si.dcInfo && si.dcInfo.amount;
                    }
                })
            }

            $scope.editApply = function (item) {
                $scope.fileList = [];
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.orderObj = data;
                    $scope.fileList = handleAttachFileList($scope.orderObj.headerInfo.attachFileList);
                    $scope.orderObj.headerInfo.purchaseOrgId = $scope.orderObj.headerInfo.customerId;
                    if (!data.headerInfo.dispatcherName) {
                        $scope.orderObj.headerInfo.dispatcherName = $scope.curUser.name;
                    }
                    if (!data.headerInfo.sapTypeName) {
                        $scope.orderObj.headerInfo.sapTypeName = "Z01";
                    }
                    if (!data.headerInfo.settleTypeName) {
                        $scope.orderObj.headerInfo.settleTypeName = "寄付";
                    }
                    if (data.headerInfo.sourceType == 1) {
                        handleMaterialDetailsWhenSourceType1(true)
                    }
                    angular.forEach($scope.orderObj.detailList, function (item) {
                      item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.orderObj.headerInfo.planDeliveryReceiptTime= $filter("YbDate")($scope.orderObj.headerInfo.planDeliveryReceiptTime, 'yyyy-MM-dd HH:mm:ss');
                    $scope.changeTab(2);
                });
            };

            $scope.adjustApply = function (item) {
                $scope.fileList = [];
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.fileList = handleAttachFileList($scope.orderObj.headerInfo.attachFileList);
                    if (data.headerInfo.sourceType == 1) {
                        handleMaterialDetailsWhenSourceType1(false)
                    }
                    angular.forEach($scope.orderObj.detailList, function (item) {
                      item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.changeTab(4);
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    };
                    data.headerInfo.deliveryReceiptTime = $filter("YbDate")(data.headerInfo.deliveryReceiptTime, 'yyyy-MM-dd HH:mm:ss');
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.attachFileList = handleAttachFileList($scope.orderObj.headerInfo.attachFileList);
                    if (data.headerInfo.sourceType == 1) {
                        handleMaterialDetailsWhenSourceType1(false)
                    }
                    angular.forEach($scope.orderObj.detailList, function (item) {
                      item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'rowNo').isShow = true;
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'warehouseInventoryEnableNum').isShow = true;
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'demandShortfall').isShow = true;
                    $scope.changeTab(3);
                });
            }

            function handleAttachFileList(attachFileList) {
              if (!attachFileList || attachFileList.length <= 0) {
                return []
              }
              return attachFileList.map(item => {
                return {
                  fileUrl: item.fileUrl,
                  name: item.originFileName,
                  filename: item.originFileName,
                  hasUpload: true,
                }
              })
            }

            // 文件上传和查看
            $scope.openFileUploader = function () {
                ybWidget.FileUploader({fileList: $scope.fileList}).then(res => {
                  $scope.fileList = res.fileList;
                })
            };

            // 文件查看
            $scope.openFileViewer = function () {
                ybWidget.FileUploader({fileList: $scope.orderObj.headerInfo.attachFileList, Type: 'view'})
            }

            $scope.viewImage = function (item) {
                ybWidget.ViewImage({
                    FileUrl: item
                })
            };

            $scope.auditApply = function (item,type) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    if (data.headerInfo.sourceType == 1) {
                        handleMaterialDetailsWhenSourceType1(false)
                    }
                    angular.forEach($scope.orderObj.detailList, function (item) {
                      item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    if (type) {
                        $scope.btnType = true
                        data.headerInfo.auditNote = ""
                    }
                    $scope.changeTab(1);
                });
            };
            $scope.revertApply = function (item) {
                ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/threeGuaranteesPur/revert";
                    var param = {
                        id: item.id
                    };
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/threeGuaranteesPur/download",
                    importReqService: "device",
                    importReqUrl: "/threeGuaranteesPur/import",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.detailList = [];
                    $scope.orderObj.detailList = angular.copy(data);
                });
            };
            $scope.viewModels = function(val) {
            }
            $scope.$watch('orderObj.detailList.length', function () {
                setMaterialDesc();
            });
            function setMaterialDesc() {
                angular.forEach($scope.orderObj.detailList, function (item) {
                    if (!!item.materialsDesc) {
                        item.materialsDes = item.materialsDesc;
                    } else {
                        item.materialsDesc = item.materialsDes;
                    }
                });
            }

            // 上传图片
            $scope.fileList = [];
            // 组装图片和文件数据
            function getAttachFileList() {
              let attachFileList = $scope.fileList.filter(item => !!item.fileUrl).map(item =>({
                originFileName: item.filename == item.name ? item.filename : item.name,
                fileUrl: item.fileUrl,
              }))
              return attachFileList;
            }

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                $scope.orderObj.headerInfo.attachFileList = getAttachFileList();
                var service = "device";
                var reqUrl = "/threeGuaranteesPur/add";
                if (!!$scope.orderObj.headerInfo.id) {
                    reqUrl = "/threeGuaranteesPur/update";
                }
                if (type === 'submit') {
                    reqUrl = "/threeGuaranteesPur/submit";
                    if (!$scope.orderObj.detailList || $scope.orderObj.detailList.length == 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }
                }

                var listValid = true;
                for (var item of $scope.orderObj.detailList) {
                    if ($scope.isNJ && $scope.checkRequired(item, 'price')) {
                        listValid = false;
                        break;
                    }
                    if ($scope.checkRequired(item, 'purchaseQty')) {
                        listValid = false;
                        break;
                    }
                    if (!!$scope.orderObj.headerInfo.id && $scope.checkTransferAmount(item, 'transferAmount')) {
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }

                setMaterialDesc();
                var param = angular.copy($scope.orderObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };


            $scope.adjustData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/threeGuaranteesPur/adjust";

                var listValid = true;
                for (var item of $scope.orderObj.detailList) {
                    if ($scope.checkRequired(item, 'purchaseQty')) {
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }

                // 处理图片数据
                $scope.orderObj.headerInfo.attachFileList = getAttachFileList();
                setMaterialDesc();
                var param = angular.copy($scope.orderObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.auditPurchase = function (type, id, message) {
                var service = "device";
                var reqUrl =  $scope.btnType? "/threeGuaranteesPur/leaderAuditPass": "/threeGuaranteesPur/auditPass";
                if (type === "refuse") {
                    if (!message) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    reqUrl =  $scope.btnType? "/threeGuaranteesPur/leaderAuditRefused":"/threeGuaranteesPur/auditRefused";
                }
                var param = {
                    id: id,
                    auditNote: message,
                    leaderAuditNote:$scope.btnType? message: undefined
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if ( (type === "pass" && !$scope.btnType) ||   reqUrl == "/threeGuaranteesPur/leaderAuditPass") {
                        ybWidget.ShowMessage("审核成功，是否立即创建三包出库单？", MESG_TYPE.Ask).then(function () {
                            EventBus.Publish('go2otherMenuPage', {
                                name: "app.stock.guaranteesOut",
                                params: {
                                    id: resp.value
                                }
                            });
                        }, function () {

                        })
                    }

                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.orderObj.headerInfo.auditNote = "";
                });
            };


            // 查询运输方式
            function getSendMethods () {
                if ($scope.sendMethodList.length > 0) {
                    return;
                }
                var service = "device";
                var reqUrl = "/sendMethodDictionary/list";
                var param = {pId: 0};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sendMethodList = resp.value;
                })
            }

            // 选择运输方式
            $scope.sendMethodChange = function (item) {
                if (item) {
                    $scope.autoAddObj.shippingMethodId = item.code;
                } else {
                    $scope.autoAddObj.shippingMethodId = undefined;

                }
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.selectDealer = function () {
                var param = {
                    name: "申请单位",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.customerName = data.companyName;
                    $scope.orderObj.headerInfo.customerId = data.id;
                    $scope.orderObj.headerInfo.purchaseOrgId = data.dealerOrgId;
                })
            };

            $scope.selectSapName = function () {
                var param = {
                    name: "内部订单号",
                    type: "sapSel"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.sapName = data.name;
                    $scope.orderObj.headerInfo.sapId = data.code;
                })
            };

            $scope.selectDispatch = function () {
                var param = {
                    name: "三包申请调度员",
                    defaultRoleName: '',
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.dispatcherName = data.name;
                    $scope.orderObj.headerInfo.dispatcherId = data.userId;
                })
            };


            $scope.signData = function (item) {
                ybWidget.AuditMsg({
                    title: '审核',
                    validateCb: function(val, otherData) {
                        // if (!otherData.reconciliateId) {
                        //     ybWidget.ShowMessage("请选择对账人", MESG_TYPE.Error);
                        //     return false;
                        // }

                        if (!val) {
                            ybWidget.ShowMessage("请输入确认意见", MESG_TYPE.Error);
                            return false;
                        }
                        return true;
                    },
                    passCb: function(val, otherData) {
                        return handleSign(item.id, val, 1, otherData);
                    },
                    refuseCb: function(val, otherData) {
                        return handleSign(item.id, val, 2, otherData);
                    }
                })
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.countTotal = function (item, type) {
                $scope.checkRequired(item, type);

                item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.purchaseQty, item.price), 2);
            };

            $scope.checkTransferAmount = function(item, type) {
                if (!$scope.isJCH || $scope.orderObj.headerInfo.sourceType != 1) return false;

                if (!item.warehouseCode) {
                    // 没有选择（备件库存或大厂库存时，调拨数量字段不作校验）
                    return false;
                }

                if ($scope.checkRequired(item, type)) {
                    item[type+"ExceedErr"] = false;
                    return true;
                }
                return $scope.checkExceedPurchaseQty(item, type);
            };

            $scope.checkExceedPurchaseQty = function (item, type) {
                if (item[type] > item.purchaseQty) {
                    item[type+"ExceedErr"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"ExceedErr"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"ExceedErr"]
            };

            $scope.checkRequired = function (item, type) {
                if (!item[type] || item[type] == '0') {
                    item[type+"Err"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"Err"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"Err"]
            };

            $scope.showErrTip = function (item, type) {
                if (!!item[type+"Err"]||!!item[type+"ExceedErr"]) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            (function () {
                initData();
                getSendMethods();
                var guaranteesApplyBillNo = window.sessionStorage.getItem("guaranteesApplyBillNo");
                window.sessionStorage.removeItem("guaranteesApplyBillNo");
                if (!!guaranteesApplyBillNo) {
                    $scope.condition.purchaseNo = guaranteesApplyBillNo;
                    getDataList().then(function (data) {
                        viewDetail(data[0]);
                    })
                } else {
                    $scope.condition.dispatcherName = $scope.isJCH ? $scope.curUser.name : undefined;
                    getDataList();
                }
                getOrderStatues();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);

                if (!!$stateParams.guaApplyDetailVO) {
                    $scope.orderObj = $stateParams.guaApplyDetailVO.orderObj;
                    var operateNum = $stateParams.guaApplyDetailVO.operate
                    $scope.tabFlag.type = operateNum;
                    $scope.tabFlag.name = tabFlag[operateNum];
                    $scope.changeTab(operateNum);
                }
            })();
        }]);
})(window, window.angular);
